<template>
  <div class="map-lifecycle"
       id="map">
    <iframe id="mainIframe"
            ref="mainIframe"
            width="100%"
            height="100%"></iframe>
    <codeEditor :code="codeStr"
                @changeHtml="changeHtml" />
  </div>
</template>
 <style scoped>
  .map-lifecycle,
  .map {
    height: 100%;
  }
</style>
 <script>
  import $ from 'jquery'
  import codeEditor from '@/components/codeEditor';
  import { mapGetters } from 'vuex'

  export default {
    data () {
      return {
        codeStr: ''
      }
    },
    computed: {
      ...mapGetters([
        'currentUrl',
        'data'
      ])
    },
    watch: {
      currentUrl () {
        this.getHtml()
      }
    },

    mounted () {
      this.getHtml()
    },
    methods: {
      getUrl (route) {
        let path = '../../static/html/map/mapAttribute/map.html'
        this.data.forEach(item => {
          let { secondTitle } = item
          secondTitle.forEach(second => {
            let { title, contents } = second
            contents.forEach(content => {
              if (route === content.path) {
                path = content.htmlUrl
              }
            })
          })
        })
        return path
      },
      getHtml () {
        let path = this.getUrl(this.$route.path)
        $.ajax({
          type: "get",
          url: path,
          dataType: "text",
          success: (data) => {
            this.$nextTick(() => {
              this.codeStr = data;
              let pDoc = this.$refs["mainIframe"].contentWindow.document;
              pDoc.open();
              pDoc.write(data);
              pDoc.close();
            })
          }
        })
      },
      changeHtml (html) {
        let pDoc = this.$refs["mainIframe"].contentWindow.document;
        pDoc.open();
        pDoc.write(html);
        pDoc.close();
        this.codeStr = html;
      }
    },
    components: {
      codeEditor
    }
  }
</script>
